package com.t194.controller;

import com.t194.pojo.Role;
import com.t194.pojo.User;
import com.t194.service.RoleService;
import com.t194.vo.TreeNode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/sys/role")
public class RoleController {

    @Resource
    private RoleService roleService;

    private String msg;


    @GetMapping("/index")
    public String index(){
        return "sys/role";
    }

    @GetMapping(value="/list")
    @ResponseBody
    public List<Role> list(){
        List<Role> list=roleService.searchAll();
        return list;
    }

    @GetMapping("/batchDel")
    @ResponseBody
    public String batchDel(Integer[] ids){
        try{
            roleService.batchDel(ids);
            msg="删除角色成功！";
        }catch(Exception ex){
            ex.printStackTrace();
            msg="删除角色失败！";
        }
        return msg;
    }


    @GetMapping("/add")
    public String add(){

        return "sys/role_add";
    }

    @PostMapping("/add")
    public String add(Role role, HttpSession session){
       User loginUser= (User) session.getAttribute("loginUser");
        if(loginUser!=null){
            role.setCreatedBy(loginUser.getId());
        }
        role.setCreationDate(LocalDateTime.now());
        System.out.println("添加前:"+role.getId());
        roleService.add(role);
        System.out.println("添加后："+role.getId());
        return "redirect:/sys/role/index";
    }


    @PostMapping("/update")
    @ResponseBody
    public String update(Role role,HttpSession session){
        User loginUser= (User) session.getAttribute("loginUser");
        if(loginUser!=null){
            role.setModifyBy(loginUser.getId());
        }
        role.setModifyDate(LocalDateTime.now());
        try {
            roleService.update(role);
            msg="修改角色成功";
        }catch (Exception ex){
        msg="修改角色失败！";
        }
        return msg;

    }

    @GetMapping("/query4Tree")
    @ResponseBody
    public List<TreeNode> query4Tree(){
        return roleService.search4Tree();
    }

}
